#ifndef __MSGARRAY_H__
#define __MSGARRAY_H__

#include "sysy_lib.h"

#define JOB_HANDLER_MAX (1024 * 10)

typedef struct {
        struct {
                buffer_t *buf;
        } *array;

        int max;
        int count;
} msgarray_t;

inline static int msgarray_init(msgarray_t *msgarray)
{
        int ret;

        if (msgarray->array)
            return 0;

        ret = ymalloc((void **)&msgarray->array,
                      sizeof(*msgarray->array) * JOB_HANDLER_MAX);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        msgarray->max = JOB_HANDLER_MAX;
        msgarray->count = 0;

        return 0;
err_ret:
        return ret;
}

inline static int msgarray_clean(msgarray_t *msgarray)
{
        int ret;

        //YASSERT(msgarray->count == 0);

        if (msgarray->max > JOB_HANDLER_MAX) {
                ret = yrealloc((void **)&msgarray->array,
                               sizeof(*msgarray->array) * msgarray->max,
                               sizeof(*msgarray->array) *  JOB_HANDLER_MAX);
                if (unlikely(ret))
                        GOTO(err_ret, ret);

                msgarray->max =  JOB_HANDLER_MAX;
        }

        msgarray->count = 0;

        return 0;
err_ret:
        return ret;
}

inline static int msgarray_append(msgarray_t *msgarray, buffer_t *buf)
{
        int ret;

        if (msgarray->count + 1 > msgarray->max) {
                ret = yrealloc((void **)&msgarray->array,
                               sizeof(*msgarray->array) * msgarray->max,
                               sizeof(*msgarray->array) * (msgarray->max + JOB_HANDLER_MAX));
                if (unlikely(ret))
                        GOTO(err_ret, ret);

                msgarray->max += JOB_HANDLER_MAX;
        }

        msgarray->array[msgarray->count].buf = buf;
        msgarray->count++;

        return 0;
err_ret:
        return ret;
}

#endif
